import datetime
import time

import apis.IChannelApiBuilder
import apis.MidPlatformUser
import apis.StartLiveFlowBuilder
import projectConfig
from apis import *
from sdktest_module.multiTest.android_driver import AndroidDriver
from sdktest_module.multiTest.ios_driver import IOSDriver
from sdktest_module.utils.constant import *
from utils.token_utils import TokenUtils

"""
模拟一个用户，用户可以执行的操作都可以在这里调用到
把中台模块分成channel、media、liveroom、linkmic
"""


class User(apis.MidPlatformUser.MidPlatformUser):
    def __init__(self, device_info, uid, role, account, password,
                 appId=projectConfig.appId,
                 secret=projectConfig.secret,
                 start_activity=projectConfig.appStartActivity,
                 bundle_id=projectConfig.bundle_id):
        # super().__init__(device_info, start_activity, role)
        self.uid = uid
        self.account = account
        self.password = password
        self.platform = device_info.platform
        if self.platform == ANDROID:
            self.driver = AndroidDriver(device_info, start_activity, role)
        elif self.platform == IOS:
            self.driver = IOSDriver(device_info, bundle_id, role)
        mSecret = bytes(secret, encoding="utf-8")
        self.token = TokenUtils.gen_token(int(appId), mSecret, uid)

    def clearBuff(self):
        """
        清空buff
        :return:
        :rtype:
        """
        self.driver.callback_buf.clear()
        self.driver.return_buf.clear()

    def checkCallbackEmpty(self):
        """
        验证回调buffer为空
        :return:
        :rtype:
        """
        self.driver.callback_buf.check_empty()

    def createEngine(self, appId=projectConfig.appId, sceneId=0):
        """
        initialize
        Returns:

        """
        if self.platform == IOS:
            api_cmd = CreateEngineApiBuilder(self.platform).appId(appId).sceneId(sceneId).build()
            # api_cmd = '{"api":"AutoFunction.callFunction:","param_type":["NSString"],"param_value":["createEngine(1,0,1)"]}'

            self.driver.send_command(api_cmd)
            self.verifyReturn('createEngine', 'void')
        elif self.platform == ANDROID:
            api_cmd = CreateEngineApiBuilder(self.platform).appId(appId).sceneId(sceneId).build()
            self.driver.send_command(api_cmd)
            self.verifyReturn('yy.com.thunderbolt.manager.MediaManager.initialize', 0)

        # 调用构造器里面的方法，暴露给用户

    def login(self, regionCode, account, password):
        """
        登录
        """
        api_cmd = apis.StartLiveFlowBuilder.login().regionCode(regionCode).account(account).password(password).build()
        self.driver.send_command(api_cmd)

    def onCreate(self, sid, uid):
        """
        进频道
        """
        api_cmd = onCreate().uid(uid).sid(sid).build()
        self.driver.send_command(api_cmd)

    # 调用构造器里面的方法，暴露给用户
    def joinRoomInner(self):
        """
        进频道
        """
        api_cmd = joinRoom().build()
        self.driver.send_command(api_cmd)
        self.driver.callback_buf.verify_callback("onJoinRoomCallback:0", timeout=10)

    def startPositionPreview(self, position):
        """
        开始预览
        """
        api_cmd = startPreview().position(position).build()
        self.driver.send_command(api_cmd)

    def stopPreview(self):
        """
        开始预览
        """
        api_cmd = apis.StartLiveFlowBuilder.stopPreview().build()
        self.driver.send_command(api_cmd)

    def startLive(self, liveBzType):
        """
        开始直播
        """
        api_cmd = startLive().liveBzType(liveBzType).build()
        self.driver.send_command(api_cmd)
        self.driver.callback_buf.verify_callback("onStartLiveCallback:0", timeout=10)

    def startLiveInner(self, liveBzType):
        """
        开始直播
        """
        api_cmd = startLive().liveBzType(liveBzType).build()
        self.driver.send_command(api_cmd)
    # def editChannelPassword(self, topSid, password):
    #     """
    #     修改密码
    #     :param topSid:
    #     :param password:
    #     :return:
    #     """
    #     api_cmd = apis.IChannelApiBuilder.editChannelPassword().topSid(topSid).password(password).build()
    #     self.driver.send_command(api_cmd)
    #     self.driver.callback_buf.verify_callback("editChannelPassword:0", timeout=10)

    # def changeLiveRoomType(self, liveBzType):
    #     """
    #     修改密码
    #     :param topSid:
    #     :param password:
    #     :return:
    #     """
    #     api_cmd = apis.IChannelApiBuilder.changeLiveRoomType().liveBzType(liveBzType).build()
    #     self.driver.send_command(api_cmd)
    #     self.driver.callback_buf.verify_callback("changeLiveRoomType:0", timeout=10)

    # def setRoomNotice(self, uid, sid, content):
    #     """
    #     修改密码
    #     :param topSid:
    #     :param password:
    #     :return:
    #     """
    #     api_cmd = apis.IChannelApiBuilder.setRoomNotice().uid(uid).sid(sid).content(content).build()
    #     self.driver.send_command(api_cmd)
    #     self.driver.callback_buf.verify_callback("setRoomNotice:0", timeout=10)

    # def setRoomNotice(self, uid, sid, content):
    #     import apis.ChannelApi_builder
    #     # api_cmd = apis.ChannelApi_builder.SetRoomNoticeApiBuilder.uid(uid).sid(sid).content(content).callback(
    #     #     callback).build()
    #     api_cmd = apis.ChannelApi_builder.SetRoomNoticeApiBuilder().uid(uid).sid(sid).content(content).build()
    #     self.driver.send_command(api_cmd)

    # def getRoomNotice(self, uid, sid):
    #     """
    #     修改密码
    #     :param topSid:
    #     :param password:
    #     :return:
    #     """
    #     api_cmd = apis.IChannelApiBuilder.getRoomNotice().uid(uid).sid(sid).build()
    #     self.driver.send_command(api_cmd)
    #     print(self.driver.return_buf)

    def testMethod(self):
        api_cmd = apis.StartLiveFlowBuilder.sayHelloToPosition().intArray("2,3").build()
        self.driver.send_command(api_cmd)

    def test_AutoTest(self):
        api_cmd = apis.startPreview.build()

    # def startLiveFlow(self, sid, uid):
    #     """开播流程模式"""
    #     api_cmd = sayHello().text("tony").build()
    #     self.driver.send_command(api_cmd)
    #     api_cmd = onCreate().sid(sid).uid(uid).build()
    #     self.driver.send_command(api_cmd)
    #     api_cmd = joinRoom().build()
    #     self.driver.send_command(api_cmd)
    #     self.driver.callback_buf.verify_callback("onJoinRoomCallback:0", timeout=10)
    #     api_cmd = startPreview().build()
    #     self.driver.send_command(api_cmd)
    #     api_cmd = startLive().liveBzType(1).build()
    #     self.driver.send_command(api_cmd)
    #     self.driver.callback_buf.verify_callback("onStartLiveCallback:0", timeout=10)
    #     # time.sleep(1000)
    #     # while True:
    #     #     print("living")

    def sendInviteReqInner(self, inviteUid, inviteSid, position, businessType, mediaType, replaceUid, extend):
        import apis.ILinkMicApiBuilder
        api_cmd = apis.ILinkMicApiBuilder.sendInviteReq().inviteUid(inviteUid).inviteSid(inviteSid).position(
            position).businessType(businessType).mediaType(mediaType).replaceUid(replaceUid).extend(extend).callback(["sendInviteReq"]).build()
        self.driver.send_command(api_cmd)
        self.driver.callback_buf.verify_callback("sendInviteReq:0", timeout=10)

    def acceptInviteLiveInterconnectReq(self):
        import apis.ILinkMicApiBuilder
        api_cmd = apis.ILinkMicApiBuilder.acceptInviteLiveInterconnectReq().build()
        self.driver.send_command(api_cmd)

    def feedback(self, appid, version, uid, msg, logPath):
        if self.platform == ANDROID:
            api_cmd = FeedbackApiBuilder(self.platform).appid(appid).version(version).uid(uid).msg(msg).logPath(
                logPath).build()
        elif self.platform == IOS:
            api_cmd = FeedbackApiBuilder(self.platform).msg(msg).build()
        self.driver.send_command(api_cmd)
        self._verifyFeedback()

    def _verifyFeedback(self):
        if self.platform == ANDROID:
            self.driver.callback_buf.verify_callback(
                "onFeedback:0", timeout=60)
        elif self.platform == IOS:
            pass

    def getReturnValue(self, function_name):
        '''获取方法返回值'''
        value = ''
        start_time = datetime.datetime.now()
        now_time = datetime.datetime.now()
        while (now_time - start_time).seconds < 5:
            if value:
                break
            self.driver.return_buf.lock.acquire()
            for return_value in self.driver.return_buf.buf:
                if function_name in return_value:
                    value = return_value.split(function_name + ':')[1]
                    break
            self.driver.return_buf.lock.release()
            time.sleep(0.2)
            now_time = datetime.datetime.now()
        return value

    ###################################################### verify ############################################################

    def verifyCreateEngine(self):
        self.verifyOnConnectionStatus(0)
        self.verifyOnConnectionStatus(1)
        self.verifyOnNetworkTypeChanged(3)

    def verifyOnConnectionStatus(self, status):
        if self.platform == ANDROID:
            self.driver.callback_buf.verify_callback("onConnectionStatus: status: " + str(status))
        elif self.platform == IOS:
            self.driver.callback_buf.verify_callback("onConnectionStatus:" + str(status))

    def verifyOnNetworkTypeChanged(self, type):
        if self.platform == ANDROID:
            self.driver.callback_buf.verify_callback("onNetworkTypeChanged: type: " + str(type))
        elif self.platform == IOS:
            self.driver.callback_buf.verify_callback("onNetworkTypeChanged:" + str(type))

    def verifyJoinRoom(self, roomid):
        if self.platform == ANDROID:
            self.driver.callback_buf.verify_callback("onJoinRoomSuccess: Room: " + roomid + " Uid: " + self.uid)
        elif self.platform == IOS:
            self.driver.callback_buf.verify_callback("onJoinRoomSuccess: room(%s) withUid(%s)" % (roomid, self.uid))

    def verifyReturn(self, function_name, return_value):
        self.driver.return_buf.verify_return(function_name + ':' + str(return_value))

    def verifyOnInviteLiveInterconnect(self):
        self.driver.callback_buf.verify_callback("onInviteLiveInterconnect:0", timeout=10)
